<?php
if ( IPB_THIS_SCRIPT != 'admin' )
{
	print "<h1>Incorrect access</h1>You cannot access this file directly. If you have recently upgraded, make sure you upgraded 'init.php'.";
	exit();
}

class ad_category
{
	var $ipsclass;
	
	function auto_run()
	{
		if(count($this->ipsclass->cache['market_category']) == 0 && $this->ipsclass->input['do'] != 'save')
		{
			$this->ipsclass->input['do'] = 'add';
			$this->ipsclass->main_msg = "You must a category first";
		}
		
		$code_redirect = array(
								'list' => 'list_category',
								'add' => 'add_form',
								'save' => 'save_category',
								'edit' => 'edit_form',
								'delete' => 'delete_form',
								'remove' => 'delete_category',
								'order' => 'reorder_category',
							);
		if(!$code_redirect[$this->ipsclass->input['do']])
		{
			$this->ipsclass->input['do'] = 'list';
		}
		$run = $code_redirect[$this->ipsclass->input['do']];
		$this->$run();		
	}
	
	function list_category()
	{
		$this->ipsclass->input['parent'] = intval($this->ipsclass->input['parent']);
		$this->ipsclass->input['parent'] = $this->ipsclass->input['parent'] ? $this->ipsclass->input['parent'] : -1;
		
		$this->ipsclass->admin->page_title  = "Welcome to managing the ibMarket category/item";
		$this->ipsclass->admin->page_detail = "Welcome to managing the ibMarket category/item. Here you can edit or delete category along with editing and deleting items from the categories.";
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;code=category', 'List category' );
		
		if($this->ipsclass->input['parent'] != -1)
		{
			$this->ipsclass->adskin->td_header[] = array( "ID"                  , "" );
			$this->ipsclass->adskin->td_header[] = array( "Icon"                , "" );
			$this->ipsclass->adskin->td_header[] = array( "Name & Description"  , "" );
			$this->ipsclass->adskin->td_header[] = array( "BPM"                 , "" );
			$this->ipsclass->adskin->td_header[] = array( "Category Tax"        , "" );
			$this->ipsclass->adskin->td_header[] = array( "Options"             , "" );
			
			$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Parent Category");
		
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																				$this->ipsclass->input['parent'],
																				"<img src='".$this->ipsclass->market_class->image_url_path."/icons/".$this->ipsclass->cache['market_category'][$this->ipsclass->input['parent']]['cat_icon']."' />",
																				"<b>".$this->ipsclass->cache['market_category'][$this->ipsclass->input['parent']]['cat_name']."</b><br />".$this->ipsclass->cache['market_category'][$this->ipsclass->input['parent']]['cat_description'],
																				"<div align='right'>".$this->ipsclass->numbers->do_number_format($this->ipsclass->cache['market_category'][$this->ipsclass->input['parent']]['price_multiplier'])."</div>",
																				"<div align='right'>".$this->ipsclass->numbers->do_number_format($this->ipsclass->cache['market_category'][$this->ipsclass->input['parent']]['cat_tax'])."%</div>",
																				"<img id=\"menu_{$this->ipsclass->input['parent']}\" src='{$this->ipsclass->vars['board_url']}/skin_acp/IPB2_Standard/images/filebrowser_action.gif' border='0' alt='Options' class='ipd' style='float:right'/>",
																		)	);
			
			$num_items = is_array($this->ipsclass->market_class->item_by_cat[$this->ipsclass->input['parent']]) ? count($this->ipsclass->market_class->item_by_cat[$this->ipsclass->input['parent']]) : 0;
			
			$this->ipsclass->html .= "<script type=\"text/javascript\">
	menu_build_menu( \"menu_{$this->ipsclass->input['parent']}\",
  new Array(
			img_item   + ".($num_items ? "\" <a href='{$this->ipsclass->base_url}&{$this->ipsclass->form_code_js}&code=item&do=list&cat=".$this->ipsclass->input['parent']."'>View Items (".$num_items.")</a>\"" : "\" <i>No Items</i>\"").",
			img_item   + \" <a href='{$this->ipsclass->base_url}&{$this->ipsclass->form_code_js}&code=category&do=edit&cat=".$this->ipsclass->input['parent']."'>Edit Category</a>\",
			img_item   + \" <a href='{$this->ipsclass->base_url}&{$this->ipsclass->form_code_js}&code=category&do=delete&cat=".$this->ipsclass->input['parent']."'>Delete Category</a>\"
      )     );
 </script>";
			
			$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		}
		else
		{
			$this->ipsclass->html .= "<div align='center'>".$this->ipsclass->adskin->js_make_button("View all items",$this->ipsclass->base_url."&".$this->ipsclass->form_code_js."&code=item&do=list&cat=".$this->ipsclass->input['parent']."&subs=1")."</div><br />";
		}
		
		$order = array();
		for($i = 1; $i <= count($this->ipsclass->market_class->category_tree[$this->ipsclass->input['parent']]); $i++)
		{
			$order[] = array($i,$i);
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_form( array(
																	 	  	 1 => array( 'section' , 'components'      ),
																			 2 => array( 'act'     , 'market'          ),
																			 3 => array( 'code'    , 'category'        ),
																			 4 => array( 'do'      , 'order'           ),
																			 5 => array( 'parent'  , $this->ipsclass->input['parent']),
																	)		);
		
		$this->ipsclass->adskin->td_header[] = array( "ID"                  , "" );
		$this->ipsclass->adskin->td_header[] = array( "Icon"                , "" );
		$this->ipsclass->adskin->td_header[] = array( "Name & Description"  , "" );
		$this->ipsclass->adskin->td_header[] = array( "BPM"                 , "" );
		$this->ipsclass->adskin->td_header[] = array( "Category Tax"        , "" );
		$this->ipsclass->adskin->td_header[] = array( "Options"             , "" );
		$this->ipsclass->adskin->td_header[] = array( "Order"               , "" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Categories");
		
		foreach($this->ipsclass->market_class->category_tree[$this->ipsclass->input['parent']] as $id => $cat)
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																				$id,
																				"<img src='".$this->ipsclass->market_class->image_url_path."/icons/".$cat['cat_icon']."' />",
																				"<b>".$cat['cat_name']."</b><br />".$cat['cat_description'],
																				"<div align='right'>".$this->ipsclass->numbers->do_number_format($this->ipsclass->cache['market_category'][$this->ipsclass->input['parent']]['price_multiplier'])."</div>",
																				"<div align='right'>".$this->ipsclass->numbers->do_number_format($this->ipsclass->cache['market_category'][$this->ipsclass->input['parent']]['cat_tax'])."%</div>",
																				"<img id=\"menu_{$id}\" src='{$this->ipsclass->vars['board_url']}/skin_acp/IPB2_Standard/images/filebrowser_action.gif' border='0' alt='Options' class='ipd' style='float:right'/>",
																				$this->ipsclass->adskin->form_dropdown('order['.$id.']',$order,$cat['cat_order']),
																		)	);
			
			$num_items = is_array($this->ipsclass->market_class->item_by_cat[$id]) ? count($this->ipsclass->market_class->item_by_cat[$id]) : 0;
			
			$this->ipsclass->html .= "<script type=\"text/javascript\">
	menu_build_menu( \"menu_{$id}\",
  new Array(
			img_item   + ".($num_items ? "\" <a href='{$this->ipsclass->base_url}&{$this->ipsclass->form_code_js}&code=item&do=list&cat=".$id."'>View Items (".$num_items.")</a>\"" : "\" <i>No Items</i>\"").",
			img_item   + \" <a href='{$this->ipsclass->base_url}&{$this->ipsclass->form_code_js}&code=category&do=edit&cat=".$id."'>Edit Category</a>\",
			img_item   + \" <a href='{$this->ipsclass->base_url}&{$this->ipsclass->form_code_js}&code=category&do=delete&cat=".$id."'>Delete Category</a>\"
      )     );
 </script>";
			
			if(is_array($this->ipsclass->market_class->category_tree[$id]) and count($this->ipsclass->market_class->category_tree[$id]))
			{
				$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic("<div style='float:right'>".$this->ipsclass->adskin->js_make_button("View items in this category and its subcategories",$this->ipsclass->base_url."&".$this->ipsclass->form_code_js."&code=item&do=list&cat=".$id."&subs=1")."</div>|-- <a href='{$this->ipsclass->base_url}&amp;{$this->ipsclass->form_code_js}&amp;code=category&amp;parent=".$id."'>View subcategories</a>");
			}
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_form_standalone("Reorder Categories");
		
		$this->ipsclass->admin->output();
	}
	
	function category_form($id)
	{
		$icon_list = $this->ipsclass->market_class->get_file_list($this->ipsclass->market_class->image_server_path."/icons/");
		$icons[0] = array('blank.gif', 'Select A Icon');
		foreach($icon_list as $file)
		{
			if(preg_match("/(.jpg|.gif|.png)/",$file)) {
				if($file != '.' || $file  != '..') {
					$icons[] = array($file,$file);
				}
			}
		}
		
		if($id == 0)
		{
			$this->ipsclass->cache['market_category'][0]['cat_parent_id'] = -1;
			$this->ipsclass->cache['market_category'][0]['cat_name'] = "Category Name";
			$this->ipsclass->cache['market_category'][0]['cat_description'] = "Category Description";
			$this->ipsclass->cache['market_category'][0]['cat_tax'] = 0;
			$icon = $icons[mt_rand(0,count($icons)-1)][0];
		}
		else
		{
			$icon = $this->ipsclass->cache['market_category'][$id]['cat_icon'];
		}
		
		$icons[0] = array($icon,'Select A Icon');
		
		$image = $this->ipsclass->market_class->image_url_path."/icons/".$icon;
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_form( array(
																	 	  	 1 => array( 'section'   , 'components'  ),
																			 2 => array( 'act'       , 'market'      ),
																			 3 => array( 'code'      , 'category'    ),
																			 4 => array( 'do'        , 'save'        ),
																			 5 => array( 'cat_id'    , $id           ),
																	),'theAdminForm',"onsubmit='return ValidateForm()'");
		
		$this->ipsclass->adskin->td_header[] = array( "" , "" );
		$this->ipsclass->adskin->td_header[] = array( "" , "" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Category Infomation");
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																			"<b>Parent Category</b>",
																			$this->ipsclass->adskin->form_dropdown('cat_parent_id', array_merge(array(array(-1, "Make this a root category")),$this->ipsclass->market_admin->build_categories_dropdown()), $this->ipsclass->cache['market_category'][$id]['cat_parent_id']),
																	)	);
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																			"<b>Category Icon</b>",
																			$this->ipsclass->adskin->form_dropdown('cat_icon',$icons,$this->ipsclass->cache['market_category'][$id]['cat_icon'],"onChange='form_change_icon(this.value,".$id.")'") . "<img src='".$image."' name='icon_".$id."_preview' />",
																	)	);
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																			"<b>Category Name</b>",
																			$this->ipsclass->adskin->form_input('cat_name', $this->ipsclass->cache['market_category'][$id]['cat_name']),
																	)	);
		
		$description = $this->ipsclass->cache['market_category'][$id]['cat_description'];
		if ( $this->ipsclass->han_editor->method == 'rte' )
		{
			$description = $this->ipsclass->parser->convert_ipb_html_to_html( $this->ipsclass->parser->pre_display_parse( $this->ipsclass->parser->pre_db_parse( $description ) ) );
		}
		else
		{
			$description = $this->ipsclass->parser->pre_edit_parse( $this->ipsclass->parser->pre_db_parse( $description ) );
		}
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic("<b>Category Description</b><br />".$this->ipsclass->han_editor->show_editor( $description, 'cat_description' ), 'left', 'tablerow1');
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																			"<b>Category Tax</b><br />This is added on to the global tax on payment.",
																			$this->ipsclass->adskin->form_simple_input('cat_tax', $this->ipsclass->numbers->clean_number($this->ipsclass->cache['market_category'][$id]['cat_tax']))."%",
																	)	);
		
		if($id)
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																				"<b>Base Price Multiplier</b><br />This number is mutiplied to the price to get the final price.",
																				$this->ipsclass->adskin->form_simple_input('price_multiplier', $this->ipsclass->numbers->do_number_format($this->ipsclass->cache['market_category'][$id]['price_multiplier'])),
																		)	);
		}
		else
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->form_hidden(array(array('price_multiplier',1)));
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_form("Process Category");
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
	}
	
	function add_form()
	{
		$this->ipsclass->admin->page_title  = "Welcome to adding a ibMarket category";
		$this->ipsclass->admin->page_detail = "Welcome to managing the ibMarket category. Here you add a category.";
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;code=category&amp;do=add', 'Add category' );
		
		$this->category_form(0);
		
		$this->ipsclass->admin->output();
	}
	
	function save_category()
	{
		$description = $this->ipsclass->parser->pre_display_parse($this->ipsclass->parser->pre_db_parse($this->ipsclass->han_editor->process_raw_post('cat_description')));
		
		$this->ipsclass->input['cat_id'] = intval($this->ipsclass->input['cat_id']);
		if($this->ipsclass->input['cat_id'])
		{
			$func = 'do_update';
			$where = "cat_id=".$this->ipsclass->input['cat_id'];
		}
		else
		{
			$this->ipsclass->cache['market_category'][0]['cat_parent_id'] = -1;
			$func = 'do_insert';
			$where = "";
		}
		
		if($this->ipsclass->input['cat_id'] and ($this->ipsclass->input['cat_parent_id'] != -1 || $this->ipsclass->input['cat_parent_id'] != $this->ipsclass->cache['market_category'][$this->ipsclass->input['cat_id']]['cat_parent_id']))
		{
			$children = $this->_build_sub_cat_array($this->ipsclass->input['cat_id']);
			$children[] = $this->ipsclass->input['cat_id'];
			
			if(in_array($this->ipsclass->input['cat_parent_id'],$children))
			{
				$this->ipsclass->admin->error("You can't have a categories parent to be one of its children");
			}
		}
		
		$row = array(
						'cat_parent_id' => $this->ipsclass->input['cat_parent_id'],
						'cat_icon' => $this->ipsclass->input['cat_icon'],
						'cat_name' => $this->ipsclass->input['cat_name'],
						'cat_description' => $description,
						'cat_name' => $this->ipsclass->input['cat_name'],
						'cat_tax' => $this->ipsclass->input['cat_tax'],
					);
		if($func == 'do_insert')
		{
			$row['cat_order'] = count($this->ipsclass->market_class->category_tree[$this->ipsclass->input['cat_parent_id']]);
		}
		
		$this->ipsclass->DB->$func('market_categories',$row,$where);
		if($func == 'do_insert')
		{
			$this->ipsclass->input['cat_id'] = $this->ipsclass->DB->get_insert_id();
		}
		$this->ipsclass->market_class->cache_categories();
		
		$this->ipsclass->admin->save_log("ibMarket: Category ".$this->ipsclass->input['cat_name']." (ID: ".$this->ipsclass->input['cat_id'].") editted");
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=category&parent=".$this->ipsclass->input['cat_parent_id'],"Processed category done...");
	}
	
	function edit_form()
	{
		$this->ipsclass->admin->page_title  = "Welcome to editing a ibMarket category";
		$this->ipsclass->admin->page_detail = "Welcome to managing the ibMarket category. Here you can edit a category.";
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;code=category', 'List category' );
		$this->ipsclass->admin->nav[] 		= array( ''                                             , 'Edit category' );
		
		$this->category_form(intval($this->ipsclass->input['cat']));
		
		$this->ipsclass->admin->output();
	}
	
	function _build_sub_cat_array($id = -1)
	{
		$ids = array();
		if(is_array($this->ipsclass->market_class->category_tree[$id]) and count($this->ipsclass->market_class->category_tree[$id]))
		{
			foreach(array_keys($this->ipsclass->market_class->category_tree[$id]) as $cat_id)
			{
				$ids[] = $cat_id;
				$ids = array_merge($ids,$this->_build_sub_cat_array($cat_id));
			}
		}
		return $ids;
	}
	
	function delete_form()
	{
		$this->ipsclass->input['cat'] = intval($this->ipsclass->input['cat']);
		
		$this->ipsclass->admin->page_title  = "Welcome to delete a ibMarket category";
		$this->ipsclass->admin->page_detail = "Welcome to delete a ibMarket category.";
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;code=category', 'List category'   );
		$this->ipsclass->admin->nav[] 		= array( ''                                             , 'Delete category' );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_form( array(
																	 	  	 1 => array( 'section'   , 'components'      ),
																			 2 => array( 'act'       , 'market'          ),
																			 3 => array( 'code'      , 'category'        ),
																			 4 => array( 'do'        , 'remove'          ),
																			 5 => array( 'cat'       , $this->ipsclass->input['cat']),
																	)		);
		
		$this->ipsclass->adskin->td_header[] = array( "" , "" );
		$this->ipsclass->adskin->td_header[] = array( "" , "" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Required");
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																			"<b>Category Name</b>",
																			$this->ipsclass->cache['market_category'][$this->ipsclass->input['cat']]['cat_name'],
																	)	);
		
		if(is_array($this->ipsclass->market_class->item_by_cat[$this->ipsclass->input['cat']]) and count($this->ipsclass->market_class->item_by_cat[$this->ipsclass->input['cat']]))
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																				"<b>Move all items in this categories to what category?</b>",
																				$this->ipsclass->adskin->form_dropdown('new_item_cat', $this->ipsclass->market_admin->build_categories_dropdown()),
																		)	);
		}
		
		if(is_array($this->ipsclass->market_class->category_tree[$this->ipsclass->input['cat']]) and count($this->ipsclass->market_class->category_tree[$this->ipsclass->input['cat']]))
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																				"<b>Move all child categories in this categories to what category?</b>",
																				$this->ipsclass->adskin->form_dropdown('new_parent_cat', $this->ipsclass->market_admin->build_categories_dropdown()),
																		)	);
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_form("Remove Category");
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->admin->output();
	}
	
	function delete_category()
	{
		$this->ipsclass->input['cat'] = intval($this->ipsclass->input['cat']);
		
		if(count($this->ipsclass->cache['market_category']) == 1)
		{
			$this->ipsclass->admin->error("You cannot remove the last category");
		}
		
		if(is_array($this->ipsclass->market_class->category_tree[$this->ipsclass->input['cat']]) and count($this->ipsclass->market_class->category_tree[$this->ipsclass->input['cat']]))
		{
			if($this->ipsclass->input['new_parent_cat'] != -1)
			{
				$children = $this->_build_sub_cat_array($this->ipsclass->input['cat']);
				$children[] = $this->ipsclass->input['cat'];
				
				if(in_array($this->ipsclass->input['new_parent_cat'],$children))
				{
					$this->ipsclass->admin->error("You cannot move children categories to the one of the children or back to itself");
				}
			}
		}
		
		if(is_array($this->ipsclass->market_class->item_by_cat[$this->ipsclass->input['cat']]) and count($this->ipsclass->market_class->item_by_cat[$this->ipsclass->input['cat']]))
		{
			if($this->ipsclass->input['new_item_cat'] == $this->ipsclass->input['cat'] || $this->ipsclass->input['new_item_cat'] == -1)
			{
				$this->ipsclass->admin->error("You cannot move the items into a deleting category");
			}
			
			$this->ipsclass->DB->do_update('market_items',array('category'=>$this->ipsclass->input['new_item_cat']),"category=".$this->ipsclass->input['cat']);
			
			$this->ipsclass->market_class->cache_items();
		}
		
		if(is_array($this->ipsclass->market_class->category_tree[$this->ipsclass->input['cat']]) and count($this->ipsclass->market_class->category_tree[$this->ipsclass->input['cat']]))
		{
			$this->ipsclass->DB->do_update('market_categories',array('cat_parent_id'=>$this->ipsclass->input['new_parent_cat']),"cat_parent_id=".$this->ipsclass->input['cat']);
		}
		
		$this->ipsclass->DB->do_delete('market_categories',"cat_id=".$this->ipsclass->input['cat']);
		
		$this->ipsclass->market_class->cache_categories();
		
		$this->ipsclass->admin->save_log("ibMarket: Category ".$this->ipsclass->cache['market_category'][$this->ipsclass->input['cat']]['cat_name']." (ID: ".$this->ipsclass->input['cat'].") removed");
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=category","Deleting category done...");
	}
	
	function reorder_category()
	{
		$this->ipsclass->input['parent'] = intval($this->ipsclass->input['parent']);
		
		if(!is_array($this->ipsclass->market_class->category_tree[$this->ipsclass->input['parent']]) || !is_array($this->ipsclass->input['order']))
		{
			$this->ipsclass->admin->error("Invalid input");
		}
		
		foreach(array_keys($this->ipsclass->market_class->category_tree[$this->ipsclass->input['parent']]) as $id)
		{
			if(!intval($this->ipsclass->input['order'][$id]))
			{
				continue;
			}
			
			$this->ipsclass->DB->do_update('market_categories',array('cat_order'=>intval($this->ipsclass->input['order'][$id])),"cat_id=".$id);
		}
		
		$this->ipsclass->market_class->cache_categories();
		
		$this->ipsclass->admin->save_log("ibMarket: Categories reordered");
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=category","Reorder categories done...");
	}
}
?>